package com.hgc.ch04;

import com.hgc.ch01.base.PrintThreads;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by 01367627 on 2019/7/10.
 */
public class LockCase {

    private static CountDownLatch latch = new CountDownLatch(100000);
    private Lock lock = new ReentrantLock();//缺省为非公平锁，添加true参数为公平锁，公平锁效率没有非公平锁高
    private int num = 50000;

    void increment() {
        lock.lock();
        try {
            num++;
        } finally {
            lock.unlock();
        }
    }

    void decrement() {
        lock.lock();
        try {
            num--;
        } finally {
            lock.unlock();
        }
    }

    public int getNum() {
        return num;
    }

    private static class MyRunnable implements Runnable {

        private LockCase lockCase;

        public MyRunnable(LockCase lockCase) {
            this.lockCase = lockCase;
        }

        @Override
        public void run() {
            lockCase.increment();
            latch.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        LockCase lockCase = new LockCase();
        MyRunnable runnable = new MyRunnable(lockCase);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            //new Thread(runnable).start();
            fixedThreadPool.execute(runnable);
        }
        latch.await();
        System.out.println("执行花费时间：" + (System.currentTimeMillis() - start) + "ms,执行后NUM为：" + lockCase.getNum());
        PrintThreads.printThreads();
    }
}
